<template>
  <div>
      <!--修改页-->
      <el-form v-if="displayType==='edit'" label-width="95px" :rules="rules" :model="orginfo" ref="editForm">
          <el-row>
              <el-col :span="12">
                <el-form-item prop="orgName">
                    <span slot="label">
                        <span class="span-box">
                            <el-tooltip style="diaplay:inline" effect="dark" content="部门名称应该由中英文、数字、下划线组成" placement="top">
                                <i class="el-icon-question" />
                            </el-tooltip>
                            <span>部门名称</span>
                        </span>
                    </span>
                    <el-input v-model="orginfo.orgName" :disabled="ifob"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="显示顺序" prop="orderNum">
                    <el-input-number v-model="orginfo.orderNum" controls-position="right" :min="1" :max="300"></el-input-number>
                </el-form-item>
              </el-col>
          </el-row>
          <el-row>
              <el-col :span="24">
                  <el-form-item label="上级部门">
                    <el-select ref="orgEditSelect" size="medium" style="width:100%" :disabled="ifroot || ifob" v-model="orginfo.parentName" clearable placeholder="请选择部门">
                            <el-option style="display:none" label="请选择" value="0"></el-option>
                            <el-tree style="display:'inline-block'" ref="tree" 
                            :data="orgTree" :props="defaultProps" @node-click="updateParentOrg($event,'edit')"></el-tree>
                        </el-select>
                </el-form-item>
              </el-col>
          </el-row>
          <el-row>
              <el-col :span="12">
                <el-form-item label="部门状态" prop="status">
                    <el-select v-model="orginfo.status" :disabled="ifob" placeholder="状态修改">
                    <el-option label="启用" value="1"></el-option>
                    <el-option label="停用" value="0"></el-option>
                    </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="部门负责人" prop="leaderName">
                    <el-select v-model="orginfo.leaderName" clearable placeholder="请选择负责人" @visible-change="getAllUser()" @change="setLeader($event,'edit')">
                            <el-option
                            v-for="item in leaderOptions"
                            :key="item.id"
                            :label="item.username"
                            :value="item.username">
                            </el-option>
                        </el-select>
                </el-form-item>
              </el-col>
          </el-row>
          <el-row>
              <el-col :span="12">
                  <el-form-item label="负责人电话">
                    <el-input disabled v-model="orginfo.leaderPhone"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="负责人邮箱">
                    <el-input disabled v-model="orginfo.leaderEmail"></el-input>
                </el-form-item>
              </el-col>
          </el-row>
          <el-row>
              <el-col>
                  <div class="inlineBtn">
                      <el-button type="primary" @click="updateSubmit">提交</el-button>
                      <el-button @click="noUpdate">关 闭</el-button>
                  </div>
              </el-col>
          </el-row>
      </el-form>
      <!--新增页-->
      <el-form v-if="displayType==='add'" label-width="95px" class="infoInput" :rules="rules" :model="neworg" ref="addForm">
          <el-row>
              <el-col :span="12">
                <el-form-item prop="orgName">
                    <span slot="label">
                        <span class="span-box">
                            <el-tooltip style="diaplay:inline" effect="dark" content="部门名称应该由中英文、数字、下划线组成" placement="top">
                                <i class="el-icon-question" />
                            </el-tooltip>
                            <span>部门名称</span>
                        </span>
                    </span>
                    <el-input v-model="neworg.orgName" size="medium"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="显示顺序" prop="orderNum">
                    <el-input-number size="medium" v-model="neworg.orderNum" controls-position="right" :min="1" :max="300"></el-input-number>
                </el-form-item>
              </el-col>
          </el-row>
          <el-row>
              <el-col :span="24">
                  <el-form-item label="上级部门" prop="parentName">
                        <el-select ref="orgAddSelect" size="medium" style="width:100%" :disabled="ifrow" v-model="neworg.parentName" clearable placeholder="请选择部门">
                            <el-option style="display:none" label="请选择" value="0"></el-option>
                            <el-tree style="display:'inline-block'" ref="tree" 
                            :data="orgTree" :props="defaultProps" @node-click="updateParentOrg($event,'add')"></el-tree>
                        </el-select>
                </el-form-item>
              </el-col>
          </el-row>
          <el-row>
              <el-col :span="12">
                <el-form-item label="部门状态" prop="status">
                    <el-select v-model="neworg.status" size="medium" placeholder="状态修改">
                        <el-option label="启用" value="1"></el-option>
                        <el-option label="停用" value="0"></el-option>
                    </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="部门负责人" prop="leaderName">
                    <el-select v-model="neworg.leaderName" size="medium" clearable placeholder="请选择负责人" @visible-change="getAllUser()" @change="setLeader($event,'add')">
                            <el-option
                            v-for="item in leaderOptions"
                            :key="item.id"
                            :label="item.username"
                            :value="item.username">
                            </el-option>
                        </el-select>
                </el-form-item>
              </el-col>
          </el-row>
          <el-row>
              <el-col :span="12">
                  <el-form-item label="负责人电话">
                    <el-input disabled size="medium" v-model="neworg.leaderPhone"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="负责人邮箱">
                    <el-input disabled size="medium" v-model="neworg.leaderEmail"></el-input>
                </el-form-item>
              </el-col>
          </el-row>
        <el-row>
            <el-col>
                <div class="inlineBtn">
                    <el-button type="primary" @click="addSubmit">提交</el-button>
                    <el-button @click="noUpdate">关 闭</el-button>
                </div>
            </el-col>
        </el-row>
      </el-form>
  </div>
</template>

<script>
export default {
    data(){
        //组织名深度校验规则
        var validateOrgName = (rule, value, callback) => {
            //组织名校验：中英文数字下划线，组合单一都可
            const reg=/^[\u4E00-\u9FA5A-Za-z0-9_]+$/ // eslint-disable-line
            if(!reg.test(value)){
                callback(new Error('部门名只能由中英文、数字、下划线组成'));
            }else{
                callback();
            }
        };
        return{
            defaultProps: {//组织树参数配置
					children: 'children',
					label: 'label'
            },
            //组织树
			orgTree:[],
            //父组件传递的当前操作组织(待修改
            orginfo:JSON.parse(this.org),
            //修改前的父级id
            originalPID:'',
            //可供负责人选项选择的用户
            leaderOptions: [],
            //是否是全局下的一级组织
            ifroot:false,
            //是否为在组织行上新增
            ifrow:false,
            ifob:false,
            //待新增的组织
            neworg:{
                parentName:'',
                orderNum:1
            },
            //表单校验规则
            rules:{
                orgName: [
                    { required: true, message: '请输入部门名', trigger: 'blur' },
                    { min: 2, max: 8, message: '长度在 2 到 8 个字符', trigger: 'blur' },
                    { validator: validateOrgName, trigger: 'blur'}
                ],
                orderNum: [
                    { required: true, message: '请设置部门显示顺序', trigger: 'change' }
                ],
                status: [
                    { required: true, message: '请设置部门状态', trigger: 'change' }
                ],
                leaderName: [
                    { required: true, message: '请设置部门负责人', trigger: 'change' }
                ],
            },
        }
    },
    props:['org','displayType','idList','nameList','addType'],//一二级组织id和name，供修改/添加上级组织
    methods:{
        //修改父级组织
        updateParentOrg(params,type){
            //console.log("go");
            //console.log(params);
            if(type==="edit"){
                if(this.orginfo.orgid==params.id){
                    this.$message.warning("禁止套娃！")
                    return
                }
                if(params.id=="1571514747092729857"){
                    this.$message.warning("该部门为编外组织，暂不支持设置下级组织")
                    return
                }
                let flag=this.idList.includes(params.id);
                if(flag==true){
                    let index=this.idList.lastIndexOf(params.id)
                    this.orginfo.parentId=params.id
                    this.orginfo.parentName=this.nameList[index]
                    this.$refs.orgEditSelect.blur();
                }else{
                    this.$notify({
                        title: '警告',
                        message: '目前最多只支持到三级组织，请重新选择！',
                        type: 'warning'
                    });
                }
            }
            if(type==="add"){
                let flag=this.idList.includes(params.id);
                if(params.id=="1571514747092729857"){
                    this.$message.warning("该部门为编外组织，暂不支持设置下级组织")
                    return
                }
                if(flag==true){
                    let index=this.idList.lastIndexOf(params.id)
                    this.neworg.parentId=params.id
                    this.neworg.parentName=this.nameList[index]
                    //console.log(this.neworg);
                    this.$refs.orgAddSelect.blur();
                }else{
                    this.$notify({
                        title: '警告',
                        message: '目前最多只支持到三级组织，请重新选择！',
                        type: 'warning'
                    });
                }
            }
        },
        //获取所有启用的用户
        getAllUser(){
          this.request('/api/user/getAllUser').then(res=>{
            if(!res){return}
            this.leaderOptions=res.data
          })
        },
        //修改部门负责人
        setLeader(params,type){
            for (let index = 0; index < this.leaderOptions.length; index++) {
                const element = this.leaderOptions[index];
                if(params===element.username){
                    //console.log(element.phone);
                    //两种情况赋值对象不一样
                    if(type==="edit"){
                        if(element.phone!==undefined&&element.phone!==null&&element.phone!==""){
                            this.orginfo.leaderPhone=element.phone
                        }else{
                            this.orginfo.leaderPhone="暂未配置"
                        }
                        if(element.email!==undefined&&element.email!==null&&element.email!==""){
                            this.orginfo.leaderEmail=element.email
                        }else{
                            this.orginfo.leaderEmail="暂未配置"
                        }
                    }
                    if(type==="add"){
                        if(element.phone!==undefined&&element.phone!==null&&element.phone!==""){
                            this.neworg.leaderPhone=element.phone
                        }else{
                            this.neworg.leaderPhone="暂未配置"
                        }
                        if(element.email!==undefined&&element.email!==null&&element.email!==""){
                            this.neworg.leaderEmail=element.email
                        }else{
                            this.neworg.leaderEmail="暂未配置"
                        }
                    }
                    return;
                }
            }
        },
        //修改提交
        updateSubmit(){
            if(!this.checkForm('editForm')){
                return
            }
            console.log(this.orginfo);
            let params=this.orginfo;
            //有点怪，只修改状态status就是01，修改上级组织就会变成启用/禁用
            params=this.sa.displaceIntStatus(params);
            //console.log(params);
            this.request('/api/org/update',params).then(res=>{
              if(!res){return}
              this.$bus.$emit("updateOrgCallback",this.originalPID,params.parentId)
            })
        },
        //新增提交
        addSubmit(){
            //console.log(this.neworg);
            if(!this.checkForm('addForm')){
                return
            }
            let params=this.neworg;
            this.request('/api/org/add',params).then(res=>{
              if(!res){return}
              this.$bus.$emit("addOrgCallback",params.parentId)
            })
        },
        //表单提交前置校验
        checkForm(formName){
            let flag;
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    flag=true;
                    return true;
                } else {
                    flag=false
                    return false;
                }
            });
            return flag
        },
        //修改/新增取消
        noUpdate(){
            this.$bus.$emit("noUpdate")
        },
        
    },
    mounted(){ 
        //如果是全局下的一级组织，就无法修改上级组织
        if(this.displayType==="edit"&&this.orginfo.parentId==0){
            this.ifroot=true           
        }
        //console.log(this.ifroot);
        //获取组织树
        this.request('/api/org/getOrgTree').then(res=>{
          if(!res){return}
          this.orgTree=res.data;
        })
        //console.log(this.orginfo);
        //如果展示修改页则先保存修改前的父级组织id
        if(this.displayType==="edit"){
            this.originalPID=this.orginfo.parentId;
            if(this.orginfo.orgid==="1571514747092729857"){
                this.ifob=true;
            }
        }else{
            if(this.addType==="rowadd"){
                //在组织上新增则默认该组织为将要新增组织的父级组织，且不可改动
                this.neworg.parentId=this.orginfo.orgid;
                this.neworg.parentName=this.orginfo.orgName;
                this.ifrow=true
            }
        }
    }
}
</script>

<style lang="scss">
/*表单input框样式控制 */
.infoInput >div>div>div>div>div>div>input{
  width:100%;
}
</style>
<style scoped>
/*修改页按钮 */
/deep/.inlineBtn {
    text-align:center
}
</style>